#pragma once
#include <iostream>
#include <pthread.h>
#include <vector>
#include <queue>
#include <string>
#include <unistd.h>

struct ThreadInfo
{
    pthread_t _tid;
    std::string _name;
};
template <class T>
class ThreadPool
{
    const static int defaultsize = 5;
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void ThreadWakeUp()
    {
        pthread_cond_broadcast(&_cond);
    }
    bool IsEmpty()
    {
        return _tasks.empty();
    }
    std::string getthreadname(pthread_t pid)
    {
        for (const auto &e : _Info)
        {
            if (e._tid == pid)
            {
                return e._name;
            }
        }
        return "NULL";
    }
    static void *Handle(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        std::string name = tp->getthreadname(pthread_self());
        while (true)
        {
            // sleep(100);
            if (tp->_Info[0]._name == name)
                sleep(100);
            else if (tp->_Info[1]._name == name)
                sleep(10);

            else if (tp->_Info[2]._name == name)
                sleep(5);
            else if (tp->_Info[3]._name == name)
                sleep(2);

            tp->Lock();
            while (tp->IsEmpty())
            {
                tp->ThreadSleep();
            }
            // 消费任务
            T t = tp->pop();

            tp->UnLock();
            // 处理任务
            t();
            std::cout << name << "  " << "run" << " " << "result" << " " << t.getresult() << std::endl;
        }
    }

public:
    ThreadPool(int num = defaultsize) : _Info(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    T pop()
    {
        T out = _tasks.front();
        _tasks.pop();
        return out;
    }
    void push(const T &in)
    {
        Lock();
        _tasks.push(in);
        ThreadWakeUp();
        UnLock();
    }
    void start()
    {
        int num = _Info.size();
        for (int i = 0; i < num; i++)
        {
            _Info[i]._name = "thread-" + std::to_string(i + 1);
            pthread_create(&_Info[i]._tid, nullptr, Handle, this);
            std::cout << "创建线程：" << i << " " << _Info[i]._name << _Info[i]._tid << std::endl;
        }
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    // 线程信息
    std::vector<ThreadInfo> _Info;
    // 任务队列
    std::queue<T> _tasks;
    // 锁
    pthread_mutex_t _mutex;
    // 条件变量
    pthread_cond_t _cond;
};
